<template>
  <div class="send-notification">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">发送通知</span>
          <el-button type="primary" @click="handleSend" :loading="sending">
            <el-icon><Promotion /></el-icon>
            发送通知
          </el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="notification-form"
      >
        <!-- 发送方式 -->
        <el-form-item label="发送方式" prop="sendType">
          <el-radio-group v-model="form.sendType" @change="handleSendTypeChange">
            <el-radio value="single">单个发送</el-radio>
            <el-radio value="bulk">批量发送</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 接收人选择 -->
        <el-form-item 
          :label="form.sendType === 'single' ? '接收人' : '接收人列表'" 
          :prop="form.sendType === 'single' ? 'recipientId' : 'recipientIds'"
        >
          <el-select
            v-if="form.sendType === 'single'"
            v-model="form.recipientId"
            placeholder="请选择接收人"
            filterable
            remote
            reserve-keyword
            :remote-method="searchUsers"
            :loading="userLoading"
            style="width: 100%"
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="`${user.full_name} (${user.username}) - ${getRoleLabel(user.role)}`"
              :value="user.id"
            />
          </el-select>

          <el-select
            v-else
            v-model="form.recipientIds"
            placeholder="请选择接收人"
            multiple
            filterable
            remote
            reserve-keyword
            :remote-method="searchUsers"
            :loading="userLoading"
            style="width: 100%"
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="`${user.full_name} (${user.username}) - ${getRoleLabel(user.role)}`"
              :value="user.id"
            />
          </el-select>
        </el-form-item>

        <!-- 通知类型 -->
        <el-form-item label="通知类型" prop="notificationType">
          <el-select v-model="form.notificationType" placeholder="请选择通知类型" style="width: 100%">
            <el-option
              v-for="type in NOTIFICATION_TYPES"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>

        <!-- 优先级 -->
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="form.priority" placeholder="请选择优先级" style="width: 100%">
            <el-option
              v-for="priority in NOTIFICATION_PRIORITIES"
              :key="priority.value"
              :label="priority.label"
              :value="priority.value"
            />
          </el-select>
        </el-form-item>

        <!-- 通知标题 -->
        <el-form-item label="通知标题" prop="title">
          <el-input
            v-model="form.title"
            placeholder="请输入通知标题"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <!-- 通知内容 -->
        <el-form-item label="通知内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            placeholder="请输入通知内容"
            :rows="6"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 预览区域 -->
    <el-card class="preview-card" v-if="form.title || form.content">
      <template #header>
        <span class="title">通知预览</span>
      </template>

      <div class="notification-preview">
        <div class="preview-header">
          <div class="preview-icon">
            <el-icon :color="getPriorityColor(form.priority)">
              <component :is="getNotificationTypeIcon(form.notificationType)" />
            </el-icon>
          </div>
          <div class="preview-meta">
            <div class="preview-title">{{ form.title || '通知标题' }}</div>
            <div class="preview-info">
              <el-tag :type="getPriorityTagType(form.priority)" size="small">
                {{ getPriorityLabel(form.priority) }}
              </el-tag>
              <span class="type-label">{{ getNotificationTypeLabel(form.notificationType) }}</span>
            </div>
          </div>
        </div>
        <div class="preview-content">
          {{ form.content || '通知内容' }}
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { 
  notificationApi, 
  type UserSimple,
  NOTIFICATION_TYPES,
  NOTIFICATION_PRIORITIES,
  getNotificationTypeLabel,
  getPriorityLabel,
  getPriorityColor,
  getNotificationTypeIcon
} from '@/api/notifications'

const router = useRouter()

// 表单引用
const formRef = ref<FormInstance>()

// 响应式数据
const sending = ref(false)
const userLoading = ref(false)
const userList = ref<UserSimple[]>([])

// 表单数据
const form = reactive({
  sendType: 'single',
  recipientId: null as number | null,
  recipientIds: [] as number[],
  notificationType: 'system',
  priority: 'normal',
  title: '',
  content: ''
})

// 表单验证规则
const rules: FormRules = {
  sendType: [
    { required: true, message: '请选择发送方式', trigger: 'change' }
  ],
  recipientId: [
    { required: true, message: '请选择接收人', trigger: 'change' }
  ],
  recipientIds: [
    {
      required: true,
      type: 'array',
      min: 1,
      message: '请至少选择一个接收人',
      trigger: 'change',
      validator: (rule: any, value: any[], callback: any) => {
        if (!value || value.length === 0) {
          callback(new Error('请至少选择一个接收人'))
        } else {
          const validValues = value.filter(v => v !== null && v !== undefined)
          if (validValues.length === 0) {
            callback(new Error('请选择有效的接收人'))
          } else {
            callback()
          }
        }
      }
    }
  ],
  notificationType: [
    { required: true, message: '请选择通知类型', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入通知标题', trigger: 'blur' },
    { min: 1, max: 200, message: '标题长度在 1 到 200 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入通知内容', trigger: 'blur' },
    { min: 1, max: 1000, message: '内容长度在 1 到 1000 个字符', trigger: 'blur' }
  ]
}

// 获取角色标签
const getRoleLabel = (role: string): string => {
  const roleLabels: Record<string, string> = {
    admin: '管理员',
    teacher: '老师',
    student: '学生'
  }
  return roleLabels[role] || role
}

// 获取优先级标签类型
const getPriorityTagType = (priority: string): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  const types: Record<string, 'primary' | 'success' | 'warning' | 'info' | 'danger'> = {
    low: 'info',
    normal: 'primary',
    high: 'warning',
    urgent: 'danger'
  }
  return types[priority] || 'primary'
}

// 搜索用户
const searchUsers = async (query: string = '') => {
  userLoading.value = true
  try {
    console.log('正在获取用户列表，搜索条件:', query)
    const response = await notificationApi.getUsersForNotification({
      search: query
    })
    console.log('用户列表响应:', response)
    // request模块返回完整的AxiosResponse，需要访问data属性
    userList.value = response.data || []
    console.log('用户列表已更新:', userList.value)
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    userLoading.value = false
  }
}

// 处理发送方式变化
const handleSendTypeChange = () => {
  // 清空接收人选择
  form.recipientId = null
  form.recipientIds = []
}

// 发送通知
const handleSend = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    await ElMessageBox.confirm(
      `确定要发送这条通知吗？${form.sendType === 'bulk' ? `将发送给 ${form.recipientIds.length} 个用户。` : ''}`,
      '确认发送',
      {
        confirmButtonText: '确定发送',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    sending.value = true

    if (form.sendType === 'single') {
      // 单个发送
      await notificationApi.sendNotification({
        recipient_id: form.recipientId!,
        notification_type: form.notificationType,
        title: form.title,
        content: form.content,
        priority: form.priority
      })
      ElMessage.success('通知发送成功')
    } else {
      // 批量发送 - 过滤掉无效值
      const validRecipientIds = form.recipientIds.filter(id => id !== null && id !== undefined)

      if (validRecipientIds.length === 0) {
        ElMessage.error('请选择至少一个接收人')
        return
      }

      await notificationApi.sendBulkNotification({
        recipient_ids: validRecipientIds,
        notification_type: form.notificationType,
        title: form.title,
        content: form.content,
        priority: form.priority
      })
      ElMessage.success(`通知发送成功，共发送给 ${validRecipientIds.length} 个用户`)
    }

    // 重置表单
    formRef.value.resetFields()
    form.recipientId = null
    form.recipientIds = []

  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('发送通知失败:', error)
      if (error.response && error.response.data) {
        console.error('错误详情:', error.response.data)
        const errorMsg = error.response.data.message ||
                        JSON.stringify(error.response.data) ||
                        '发送失败'
        ElMessage.error(errorMsg)
      } else {
        ElMessage.error('发送失败')
      }
    }
  } finally {
    sending.value = false
  }
}

// 生命周期
onMounted(() => {
  searchUsers()
})
</script>

<style lang="scss" scoped>
.send-notification {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 18px;
      font-weight: 600;
      color: var(--text-color-primary);
    }
  }

  .notification-form {
    max-width: 800px;
  }

  .preview-card {
    margin-top: 20px;

    .notification-preview {
      .preview-header {
        display: flex;
        align-items: flex-start;
        margin-bottom: 12px;

        .preview-icon {
          margin-right: 12px;
          margin-top: 2px;

          .el-icon {
            font-size: 20px;
          }
        }

        .preview-meta {
          flex: 1;

          .preview-title {
            font-size: 16px;
            font-weight: 600;
            color: var(--text-color-primary);
            margin-bottom: 6px;
          }

          .preview-info {
            display: flex;
            align-items: center;
            gap: 8px;

            .type-label {
              font-size: 12px;
              color: var(--text-color-secondary);
            }
          }
        }
      }

      .preview-content {
        padding: 12px;
        background: var(--fill-color-extra-light);
        border-radius: 6px;
        color: var(--text-color-regular);
        line-height: 1.6;
        white-space: pre-wrap;
      }
    }
  }
}
</style>
